import requests
from retrying import retry

num = 1


@retry(stop_max_attempt_number=3)
def _parse_url(url):
    global num
    print("第%d次尝试" % num)
    num += 1
    headers = {
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
    }
    # 超时的时候会报错并重试
    r = requests.get(url, headers=headers, timeout=3)
    # 状态码不是200，也会报错并重试
    assert r.status_code == 200  # 此语句是"断言"，如果assert 后面的条件为True则呈现继续运行，否则抛出异常
    return r


def parse_url(url):
    # 进行异常捕获
    try:
        r = _parse_url(url)
    except Exception as e:
        print("产生异常：", e)
        # 报错返回None
        r = None
    return r


if __name__ == '__main__':
    url = "https://chinasoftinc.com/owa"
    # url = "https://www.baidu.com"
    print("----开始----")
    r = parse_url(url=url)
    print("----结束----", "响应内容为：", r)
